import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/LiveRoomItem.dart';
import 'package:toys_flutter/components/MyIconButton.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';

class LivesPage extends StatefulWidget {
  const LivesPage({super.key});

  @override
  State<LivesPage> createState() => _LivesPageState();
}

class _LivesPageState extends State<LivesPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin<LivesPage> {
  @override
  bool get wantKeepAlive => true;

  final Color colorMain = const Color.fromRGBO(255, 229, 143, 1);
  int tabIndex = 0;
  List<Map<String, dynamic>> _navList = [];
  List<dynamic> _list = [];
  bool isMore = true;
  final Map<String, dynamic> _params = {
    'page_no': 1,
    'cid': "",
    'is_recommend': 1,
  };
  late TabController _tabController;
  late ScrollController _scrollController;

  Future<void> _getNavData() async {
    try {
      var res = await Api.toysGetLiveCategory();
      if (res['code'] == 1) {
        setState(() {
          _navList = List<Map<String, dynamic>>.from(res['data']['data']);
          _navList.insert(0, {'title': '热门推荐', 'id': '00001'});
          _navList.insert(1, {'title': '最新', 'id': '00002'});
        });
      } else {
        TDToast.showText('加载分类失败', context: context);
      }
    } catch (e) {
      TDToast.showText('加载分类异常: $e', context: context);
    }
  }

  Future<void> _initData(bool add) async {
    var res = await Api.liveRecommendLists(_params);
    if (res['code'] == 1) {
      var list = List<Map<String, dynamic>>.from(res['data']['list']);
      setState(() {
        if (add) {
          _list.addAll(list);
        } else {
          _list = list;
        }
        isMore = res['data']['more'] != 0;
      });
    } else {
      TDToast.showText('加载数据失败', context: context);
    }
  }

  void getData(bool add) async {
    var res = await Api.liveLists(_params);
    if (res['code'] == 1) {
      var list = List<Map<String, dynamic>>.from(res['data']['list']);
      setState(() {
        if (add) {
          _list.addAll(list);
        } else {
          _list = list;
        }
        isMore = res['data']['more'] != 0;
      });
    } else {
      TDToast.showText('加载数据失败', context: context);
    }
  }

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _initialize();
  }

  Future<void> _initialize() async {
    await _getNavData();
    _tabController = TabController(length: _navList.length, vsync: this);
    _initData(false);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _refreshData() async {
    _params['page_no'] = 1;
    isMore = true;
    _initialize();
    if (tabIndex == 0 || tabIndex == 1) {
      _initData(false);
    } else {
      getData(false);
    }
  }

  Future<void> _onLoadMore() async {
    if (!isMore) return;
    _params['page_no']++;
    if (tabIndex == 0 || tabIndex == 1) {
      _initData(true);
    } else {
      getData(true);
    }
  }

  void _handleTap(Map<String, dynamic> item) async {
    final String id = item['id'].toString();
  }

  void _onTabTapped(int index) {
    setState(() {
      tabIndex = index;
      _params['page_no'] = 1;
      _params['cid'] = '';
      isMore = true;
      // _scrollController.jumpTo(0); // 切换Tab时滚动到顶部

      if (index == 0) {
        _params['is_recommend'] = 1;
        _initData(false);
      } else if (index == 1) {
        _params['is_recommend'] = 0;
        _initData(false);
      } else {
        _params['cid'] = _navList[index]['id'];
        getData(false);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: _navList.length,
        initialIndex: 0,
        child: Scaffold(
          appBar: AppBar(
            title: const Text('直播', style: TextStyle(fontSize: 16)),
            backgroundColor: colorMain,
            actions: const [
              Padding(
                padding: EdgeInsets.only(right: 15),
                child: MyIconButton(icon: Icons.search),
              ),
            ],
          ),
          body: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  colorMain,
                  Colors.white,
                  Colors.white,
                  Colors.white,
                ],
              ),
            ),
            child: Column(
              children: [
                if (_navList.isNotEmpty)
                  TDTabBar(
                    tabs: _navList
                        .map((item) => TDTab(text: item['title'].toString()))
                        .toList(),
                    controller: _tabController,
                    isScrollable: true,
                    showIndicator: true,
                    dividerHeight: 0,
                    onTap: _onTabTapped,
                  ),
                if (_navList.isEmpty)
                  const Center(
                    child: CircularProgressIndicator(),
                  ),
                Expanded(
                  child: RefreshableListView(
                    enableLoadMore: false,
                    onRefresh: _refreshData,
                    children: [
                      _buildList(context, _list),
                      TDDivider(
                        text: isMore ? '上拉加载更多' : '没有更多了',
                        alignment: TextAlignment.center,
                      ),
                      const SizedBox(height: 25),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}

Widget _buildList(BuildContext context, dynamic list) {
  var width = (MediaQuery.of(context).size.width - 0) / 2;
  return Wrap(
    children: List.generate(list.length, (index) {
      return SizedBox(
        width: width, // 每个子组件的宽度
        height: width,
        child: LiveRoomItem(item: list[index]),
      );
    }),
  );
}
